package zhoufu.sz.sanxiao_check.presents;

import android.util.SparseArray;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.Subscription;
import rx.functions.Action1;
import zhoufu.sz.sanxiao_check.event.Event;
import zhoufu.sz.sanxiao_check.event.RxBus;
import zhoufu.sz.sanxiao_check.models.GrandCountModel;
import zhoufu.sz.sanxiao_check.models.ReseauModel;
import zhoufu.sz.sanxiao_check.net.RequestHelper;
import zhoufu.sz.sanxiao_check.net.RequestRepository;
import zhoufu.sz.sanxiao_check.ui.contract.MainContract;
import zhoufu.sz.sanxiao_check.utils.SharedPreferencesUtil;

/**
 * User:RCP
 * email:ruancaipu@gmail.com
 * Date:2016/7/20
 */
public class MainPresenter implements MainContract.Presenter {
  private RequestRepository _requestHelper;

  private List<ReseauModel> mList;

  private MainContract.View view;

  private int mCurrentID;

  private SparseArray<List<ReseauModel>> array;

  private int rightPosition;

  private SharedPreferencesUtil mPreferencesUtil;

  private String District;//片区ID

  private int Status = 0;

  private String DistrictName;

  @Inject
  public MainPresenter(RequestRepository _requestHelper, SharedPreferencesUtil mPreferencesUtil) {
    this._requestHelper = _requestHelper;
    this.mPreferencesUtil = mPreferencesUtil;
    array = new SparseArray();
    District = "0";
    DistrictName = "所有片区";
    busEvent();
  }

  public void bindView(MainContract.View view) {
    this.view = view;
  }

  private void busEvent() {
    Subscription subscription = RxBus.getDefault()
        .toObserverable(Event.LocationEvent.class)
        .subscribe(new Action1<Event.LocationEvent>() {
          @Override public void call(Event.LocationEvent locationEvent) {
            _requestHelper.AddPlease(locationEvent.getLongitude(), locationEvent.getLatitude(),
                new RequestHelper.RequestCallBack() {
                  @Override public void onPullStart() {

                  }

                  @Override public void onPullFailud(Throwable throwable) {

                  }

                  @Override public void onPullEnd() {

                  }

                  @Override public void onPullSuccessed(Object s) {

                  }
                });
          }
        });
    _requestHelper.addSubscribe(subscription);
  }

  public void gradeData(String District) {
    if (District == null) District = String.valueOf(this.District);
    _requestHelper.GetGrade(Status, District, new RequestHelper.RequestCallBack<GrandCountModel>() {
      @Override public void onPullStart() {

      }

      @Override public void onPullFailud(Throwable throwable) {
      }

      @Override public void onPullEnd() {

      }

      @Override public void onPullSuccessed(GrandCountModel s) {
        if (s.isSuccess()) {
          if (s.getData().size() > 0) {
            view.setTabData(s.getData().get(0));
            //缓存初始状态的数据
            if ("0".equals(MainPresenter.this.District) && Status == 0) {
              mPreferencesUtil.saveEntity(s.getData().get(0), "GetGrade");
            }
          }
        } else {
          view.showToast(s.getErrMsg());
        }
      }
    });
  }

  @Override public void onStart() {
    ReseauModel remodel =
        (ReseauModel) mPreferencesUtil.readEntity("GetGridList", ReseauModel.class);
    if (remodel != null) {
      mList = remodel.getData();

      setGridListData();
    }

    GrandCountModel data =
        (GrandCountModel) mPreferencesUtil.readEntity("GetGrade", GrandCountModel.class);
    if (null != data) {
      view.setTabData(data);
    } else {
      view.setTabData(new GrandCountModel());
    }
    _requestHelper.GetGridList(new RequestHelper.RequestCallBack<ReseauModel>() {
      @Override public void onPullStart() {

      }

      @Override public void onPullFailud(Throwable throwable) {
      }

      @Override public void onPullEnd() {

      }

      @Override public void onPullSuccessed(ReseauModel s) {
        if (s.isSuccess()) {
          mList = s.getData();
          mPreferencesUtil.saveEntity(s, "GetGridList");
          setGridListData();
        } else {
          view.showToast(s.getErrMsg());
        }
      }
    });
    gradeData(null);
  }

  private void setGridListData() {
    if (mList != null && mList.size() > 0) {
      List<ReseauModel> reseauModelList = new ArrayList<ReseauModel>();
      ReseauModel rModel = new ReseauModel();
      rModel.setName("所有片区");
      rModel.setID(0);
      reseauModelList.add(rModel);
      array.put(0, reseauModelList);
      for (int i = 0; i < mList.size(); i++) {
        if (mList.get(i).getDistrictList() != null) {
          mList.get(i).getDistrictList().add(0, new ReseauModel("所有片区", 0, mList.get(i).getID()));
        }
        array.put(i + 1, mList.get(i).getDistrictList());
      }
      if (array.size() > 0) {
        mCurrentID = 0;
        view.setRightAdapter(array.get(mCurrentID));
      }
      ReseauModel reseauModel = new ReseauModel();
      reseauModel.setID(0);
      reseauModel.setName("所有网格");
      mList.add(0, reseauModel);
      view.setLeftAdapter(mList);
    }
  }

  @Override public void onPause() {

  }

  @Override public void onDestroy() {
    _requestHelper.onDestory();
  }

  @Override public void checkLeft(int position) {
    if (mList == null) {
      return;
    }
    mCurrentID = position;
    if (array.indexOfKey(position) > -1) {
      view.setRightAdapter(array.get(position));
    }
  }

  @Override public ReseauModel checkRight(int position) {
    rightPosition = position;
    if (array.size() == 0 || array.get(mCurrentID).size() == 0) {
      return new ReseauModel();
    }
    ReseauModel model = array.get(mCurrentID).get(position);
    District = model.getID() + "";
    DistrictName = model.getName();
    StringBuilder sb = new StringBuilder(String.valueOf(District));
    if (model.getID() == 0 && mCurrentID > 0) {
      List<ReseauModel> reseauModels = array.get(mCurrentID);
      if (reseauModels != null) {
        sb.delete(0, sb.length());
        for (int i = 1; i < reseauModels.size(); i++) {
          sb.append(reseauModels.get(i).getID()).append(",");
        }
        if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
      }
    }
    District = sb.toString();
    gradeData(sb.toString());
    model.setSuperID(mList.get(mCurrentID).getID());
    model.setSuperName(mList.get(mCurrentID).getName());
    return model;
  }

  public String getDistrictName() {
    return DistrictName;
  }

  public String getDistrict() {
    return District;
  }

  public void setDistrict(String district) {
    District = district;
  }

  public int getStatus() {
    return Status;
  }

  public void setStatus(int status) {
    Status = status;
  }
}
